package com.cms.template.method;

import com.cms.utils.FreeMarkerUtils;
import freemarker.ext.beans.DateModel;
import freemarker.ext.beans.StringModel;
import freemarker.template.SimpleDate;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

/**
 * 模板方法 - 日期
 *
 *
 *
 */
@Component
public class DateMethod implements TemplateMethodModelEx {

    /**
     * 执行
     *
     * @param arguments
     *            参数
     * @return 结果
     */
    @SuppressWarnings("rawtypes")
    public Object exec(List arguments) throws TemplateModelException {
        if(arguments.get(0)==null){
            return "";
        }
        Object dateObj = arguments.get(0);
        Date date = null;
        if(dateObj instanceof StringModel){
            Object wrappedObject = ((StringModel) arguments.get(0)).getWrappedObject();
            ZonedDateTime zonedDateTime = ((LocalDateTime)wrappedObject).atZone(ZoneId.systemDefault());
            date = Date.from(zonedDateTime.toInstant());
        }
        String format = FreeMarkerUtils.getArgument(1, String.class, arguments);
        return DateFormatUtils.format(date,format);
    }

}
